#!/usr/bin/env node

const API_BASE = 'http://localhost:3002/api/v1';

async function makeRequest(url, options = {}) {
  try {
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    });
    
    const data = await response.json();
    console.log(`${options.method || 'GET'} ${url}`);
    console.log(`Status: ${response.status}`);
    console.log('Response:', JSON.stringify(data, null, 2));
    console.log('---');
    
    return { response, data };
  } catch (error) {
    console.error('Request failed:', error.message);
    return null;
  }
}

async function testAdminFunctions() {
  console.log('🔧 Testing Admin Functions\n');

  // 1. 首先创建一个管理员用户
  console.log('1. Create admin user');
  const registerResult = await makeRequest(`${API_BASE}/auth/register`, {
    method: 'POST',
    body: JSON.stringify({
      username: 'admin',
      email: 'admin@example.com',
      password: 'admin123',
      displayName: 'System Administrator'
    })
  });

  if (!registerResult || !registerResult.data.success) {
    console.error('❌ Admin registration failed');
    return;
  }

  // 2. 手动将用户设置为管理员（在实际应用中这应该通过数据库操作完成）
  console.log('2. Login as admin');
  const loginResult = await makeRequest(`${API_BASE}/auth/login`, {
    method: 'POST',
    body: JSON.stringify({
      email: 'admin@example.com',
      password: 'admin123'
    })
  });

  if (!loginResult || !loginResult.data.success) {
    console.error('❌ Admin login failed');
    return;
  }

  const adminToken = loginResult.data.data.tokens.accessToken;
  console.log('✅ Admin login successful\n');

  // 3. 测试系统统计
  console.log('3. Get system statistics');
  await makeRequest(`${API_BASE}/admin/stats`, {
    headers: {
      'Authorization': `Bearer ${adminToken}`
    }
  });

  // 4. 测试获取待审核插件
  console.log('4. Get pending plugins');
  await makeRequest(`${API_BASE}/admin/plugins/pending`, {
    headers: {
      'Authorization': `Bearer ${adminToken}`
    }
  });

  // 5. 测试获取用户列表
  console.log('5. Get users list');
  await makeRequest(`${API_BASE}/admin/users`, {
    headers: {
      'Authorization': `Bearer ${adminToken}`
    }
  });

  // 6. 测试获取审计日志
  console.log('6. Get audit logs');
  await makeRequest(`${API_BASE}/admin/audit-logs`, {
    headers: {
      'Authorization': `Bearer ${adminToken}`
    }
  });

  // 7. 测试用户搜索
  console.log('7. Search users');
  await makeRequest(`${API_BASE}/admin/users?search=test&page=1&limit=10`, {
    headers: {
      'Authorization': `Bearer ${adminToken}`
    }
  });

  // 8. 测试非管理员访问（应该失败）
  console.log('8. Test non-admin access (should fail)');
  const userLoginResult = await makeRequest(`${API_BASE}/auth/login`, {
    method: 'POST',
    body: JSON.stringify({
      email: 'testdev@example.com',
      password: 'password123'
    })
  });

  if (userLoginResult && userLoginResult.data.success) {
    const userToken = userLoginResult.data.data.tokens.accessToken;
    await makeRequest(`${API_BASE}/admin/stats`, {
      headers: {
        'Authorization': `Bearer ${userToken}`
      }
    });
  }

  console.log('🎉 Admin function testing completed!');
}

// 运行测试
testAdminFunctions().catch(console.error);
